package com.duojuhe.security.xss;

import com.duojuhe.common.config.DuoJuHeConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.servlet.DispatcherType;
import java.util.HashMap;
import java.util.Map;

/**
 * Filter配置
 */
@Configuration
public class XssFilterConfig {
    @Resource
    private DuoJuHeConfig duoJuHeConfig;

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Bean
    public FilterRegistrationBean xssFilterRegistration() {
        //匹配链接 也就是需要拦截的链接
        String urlPatterns = "/*";
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new XssFilter());
        registration.addUrlPatterns(StringUtils.split(urlPatterns, ","));
        registration.setName("xssFilter");
        registration.setOrder(Integer.MAX_VALUE);
        Map<String, String> initParameters = new HashMap<String, String>();
        initParameters.put("enabled", "true");
        initParameters.put("tokenExpiresIn", String.valueOf(duoJuHeConfig.getTokenExpiresIn()));
        registration.setInitParameters(initParameters);
        return registration;
    }
}
